<template>
    <Modal :mask-closable="false" v-model="addView" :title="edit? '新增': '编辑'" width="888" @on-cancel="handleCancel">
        <Form :label-width="100" :model="dataparams" :rules="ruleValidate" ref="formItem">
            <FormItem label="计划标题" prop="title"><Input v-model="dataparams.title" placeholder="请输入视图标题，10个字以内"
                    maxlength="10" /></FormItem>
            <div class="sky-tit">筛选条件</div>
            <Row :gutter="16">
                <Col span="12">
                <FormItem label="创建时间">
                    <DatePicker :editable="false" type="daterange" :options="options" v-model="timers" placeholder="请选择患者创建时间"
                        @on-change="screentask" />
                </FormItem>
                </Col>
                <Col span="12">
                <FormItem label="病种">
                    <!-- <Select multiple v-model="dataparams.patient_diseases_id" @on-change="screentask"> 
                        <Option :value="item.value" v-for="item in diseasesList" :key="item.value">{{item.label}}</Option> 
                    </Select>  -->
                    <TreeSelect :max-tag-count="3" v-model="dataparams.patient_diseases_id" :data="diseasesList" filterable
                            multiple @on-change="screentask"/>
                </FormItem>
                </Col>
                <Col span="12">
                <FormItem label="渠道">
                    <Select multiple filterable v-model="dataparams.channel_id" @on-change="screentask">
                        <OptionGroup :label="item.label" v-for="item in sourcechannelList" :key="item.value">
                            <Option :value="items.value" v-for="items in item.children" :key="items.value">
                                {{items.label}}</Option>
                        </OptionGroup>
                    </Select>
                </FormItem>
                </Col>
                <Col span="12">
                <FormItem label="城市">
                    <Select v-model="dataparams.city_id" placeholder="请输入城市" filterable remote multiple clearable
                        :remote-method="remoteMethod" :loading="loadingcity" @on-change="screentask">
                        <Option v-for="(item, index) in optionscity" :key="index" :value="item.value"
                            :label="item.label">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                </Col>
                <Col span="12">
                <FormItem label="年龄">
                    <InputNumber class="ivu-mr-16" placeholder="请输入" :max="199" :min="0" :step="1"
                        @on-change="inputblurmin" v-model="dataparams.min_age" :formatter="ins"></InputNumber>
                    <span class="ivu-ml-8 ivu-mr-8">-</span>
                    <InputNumber placeholder="请输入" :max="199" :min="0" :step="1" v-model="dataparams.max_age"
                        :formatter="ins" @on-change="inputblurmax"></InputNumber>
                </FormItem>
                </Col>
                <Col span="12">
                <FormItem label="患者状态">
                    <Select multiple v-model="dataparams.patient_status_id" @on-change="screentask">
                        <Option :value="item.id" v-for="item in patientstatusList" :key="item.id">{{item.status_name}}
                        </Option>
                    </Select>
                </FormItem>
                </Col>
                <Col span="24">
                <FormItem label="部位">
                    <Select multiple v-model="dataparams.body_parts_id" @on-change="screentask">
                        <Option :value="item.id" v-for="item in bodypartsList" :key="item.id">{{item.label}}</Option>
                    </Select>
                </FormItem>
                </Col>
                <Col span="12">
                <FormItem label="患者数">
                    <strong>{{total}}</strong>
                </FormItem>
                </Col>
            </Row>
            <div class="sky-tit">推送到</div>
            <FormItem :rules="{required: true, message: `请选择部门${index+1}`, trigger: 'change'}"
                v-for="(items,index) in dataparams.push_list" :prop="'push_list.' + index + '.department_id'"
                :label="`部门${index+1}`" :key="index">
                <Select v-width="118" placeholder="请选择部门" v-model="items.department_id" clearable
                    @on-change="statusselect(index, items.department_id)">
                    <Option :disabled="disabledstatus.indexOf(item.value)>-1" v-for="item in departmentList"
                        :key="item.value" :value="item.value">{{item.label}}</Option>
                </Select>
                <Select v-width="500" v-model="items.member_ids" class="ivu-ml-8" placeholder="请选择人员" multiple>
                    <Option v-for="item in items.personList" :key="item.value" :value="item.value">{{item.label}}
                    </Option>
                </Select>
                <Button v-if="dataparams.push_list.length !== 1" class="ivu-ml-8" type="default"
                    @click="handleRemove(index)">删除</Button>
            </FormItem>
            <FormItem>
                <Button type="dashed" icon="md-add" @click="handleAddItem">添加</Button>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button @click="handleCancel">取消</Button>
            <Button type="primary" :loading="loading" :disabled="isDisable" @click="handleSubmit">确定</Button>
        </div>
    </Modal>
</template>
<script>
    import { settingviewgetparamslist, settingvieweditviewcondition, settingviewpatienttotal, settingviewcreateview } from "@/api/hqapi/indexone";
    import { patientindexsearchcity } from "@/api/hqapi";
    import { getDepartmentRole } from "@/api/TApi";
    import mixincity from "@/mixins/mixincity";
    export default {
        mixins: [mixincity],
        data() {
            return {
                options: {
                    disabledDate(date) {
                        return date && date.valueOf() > Date.now();
                    }
                },
                loading: false,
                isDisable: false,
                setTimeouts: null,
                setTimeoutd: null,
                total: 0,
                city_id: '',
                loadingcity: false,
                timers: [],
                timer: null,
                addView: false,
                edit: false,
                departmentList: [],
                diseasesList: [],
                sourcechannelList: [],
                bodypartsList: [],
                patientstatusList: [],
                personList: [],
                optionscity: [],
                disabledstatus: [],
                dataparams: {
                    id: '', // 视图ID 新增时不传	是
                    title: '', // 标题 是	
                    type: 1, // 0：常规视图 1：动态视图
                    push_list: [
                        {
                            department_id: "",
                            member_ids: [],
                            personList: [],
                        }
                    ], // 推送到 [json]
                    start_time: '', // 开始时间
                    end_time: '', // 结束时间
                    patient_diseases_id: [], // 病种
                    channel_id: [], // 渠道
                    city_id: [], // 城市
                    min_age: null, // 最小年龄
                    max_age: null, // 最大年龄
                    patient_status_id: [], // 患者状态
                    body_parts_id: [], // 部位
                },
                statusList: [
                    { value: 0, label: '未开始' },
                    { value: 1, label: '进行中' },
                    { value: 2, label: '已延期' },
                    { value: 3, label: '已完成' },
                    { value: 4, label: '已关闭' },
                ],
                ruleValidate: {
                    title: [
                        { required: true, message: '请输入视图标题', trigger: 'blur' }
                    ],
                }
            };
        },
        mounted() {
            settingviewgetparamslist().then(res => {
                this.diseasesList = res.diseases_list
                this.sourcechannelList = res.source_channel_list
                this.patientstatusList = res.patient_status
                this.departmentList = res.department
                this.bodypartsList = res.body_parts_list
            })
        },
        methods: {
            defaultcityname() {
                this.optionscity = JSON.parse(JSON.stringify(this.defaultcity))
            },
            // 初始化
            initial(id) {
                this.total = 0
                this.dataparams = {
                    id: id, // 视图ID 新增时不传	是
                    title: '', // 标题 是	
                    type: 1, // 0：常规视图 1：动态视图
                    push_list: [
                        {
                            department_id: "",
                            member_ids: [],
                            personList: [],
                        }
                    ], // 推送到 [json]
                    start_time: '', // 开始时间
                    end_time: '', // 结束时间
                    patient_diseases_id: [], // 病种
                    channel_id: [], // 渠道
                    city_id: [], // 城市
                    min_age: null, // 最小年龄
                    max_age: null, // 最大年龄
                    patient_status_id: [], // 患者状态
                    body_parts_id: [], // 部位
                }
                this.timers = []
                this.disabledstatus = []
                this.$nextTick(() => {
                    this.$refs.formItem.resetFields()
                })
                this.addView = true
                this.askData(id)
            },
            // 请求数据
            askData(id) {
                if (id) {
                    this.edit = false
                    settingvieweditviewcondition({ id }).then(res => {
                        this.timers = [res.view_detail.start_time, res.view_detail.end_time]
                        this.dataparams.title = res.view_detail.title
                        this.dataparams.push_list = res.view_detail.push_list
                        this.dataparams.patient_diseases_id = res.view_detail.patient_diseases_id
                        this.dataparams.channel_id = res.view_detail.channel_id
                        this.dataparams.city_id = res.view_detail.city_id
                        if (this.dataparams.city_id.length > 0) {
                            this.optionscity = res.view_detail.city
                        }
                        if (res.view_detail.min_age === '0') {
                            this.dataparams.min_age = 0
                        } else {
                            this.dataparams.min_age = res.view_detail.min_age * 1 || null
                        }
                        if (res.view_detail.max_age === '0') {
                            this.dataparams.max_age = 0
                        } else {
                            this.dataparams.max_age = res.view_detail.max_age * 1 || null
                        }
                        this.dataparams.patient_status_id = res.view_detail.patient_status_id
                        this.dataparams.body_parts_id = res.view_detail.body_parts_id
                        this.dataparams.push_list = []
                        if (res.view_push.length > 0) {
                            for (let index in res.view_push) {
                                this.dataparams.push_list.push({
                                    department_id: res.view_push[index].department_id,
                                    member_ids: res.view_push[index].member_ids,
                                    personList: [],
                                })
                                this.departmentfun(index, res.view_push[index].department_id)
                            }
                        } else {
                            this.dataparams.push_list = [
                                {
                                    department_id: "",
                                    member_ids: [],
                                    personList: [],
                                }
                            ]
                        }
                        this.screentask()
                    })
                } else {
                    this.edit = true
                    this.screentask()
                }
            },
            departmentfun(index, department_id) {
                getDepartmentRole({ department_id }).then(res => {
                    this.dataparams.push_list[index].personList = res
                })
            },
            remoteMethod(query) {
                clearTimeout(this.timer);
                if (query !== "") {
                    let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
                    if (!reg.test(query)) {
                        return;
                    }
                    this.loadingcity = true;
                    return new Promise((resolve) => {
                        this.timer = setTimeout(() => {
                            patientindexsearchcity({
                                keywords: query,
                            }).then((res) => {
                                this.query = "";
                                if (res.list && res.list.length > 0) {
                                    let list = [];
                                    for (let item of res.list) {
                                        list.push({
                                            value: item.value,
                                            label: item.label,
                                        });
                                    }
                                    this.optionscity = list;
                                }
                                resolve(res.data);
                            });
                            this.loadingcity = false;
                        }, 200);
                    });
                }
            },
            statusselect(index, e) {
                this.disabledstatus[index] = e
                this.departmentfun(index, e)
            },
            screentask() {
                clearTimeout(this.setTimeoutd)
                this.setTimeoutd = setTimeout(() => {
                    let params = {
                        start_time: this.timers[0] || '',
                        end_time: this.timers[1] || '',
                        patient_diseases_id: this.dataparams.patient_diseases_id.join(','),
                        channel_id: this.dataparams.channel_id.join(','),
                        city_id: this.dataparams.city_id.join(','),
                        min_age: this.dataparams.min_age,
                        max_age: this.dataparams.max_age,
                        patient_status_id: this.dataparams.patient_status_id.join(','),
                        body_parts_id: this.dataparams.body_parts_id.join(','),
                    }
                    settingviewpatienttotal(params).then(res => {
                        this.total = res
                    })
                }, 500)
            },
            // 数字输入框为正整数
            ins(e) {
                return parseInt(e)
            },
            inputblurmin() {
                if (this.dataparams.min_age >= 0 && this.dataparams.max_age) {
                    if (this.dataparams.min_age > this.dataparams.max_age) {
                        this.$Message.error('请输入合理的年龄范围')
                        this.dataparams.min_age = null
                    } else {
                        this.screentask()
                    }
                }
                if (!this.dataparams.min_age && !this.dataparams.max_age) {
                    this.screentask()
                }
            },
            inputblurmax() {
                clearTimeout(this.setTimeouts)
                if (this.dataparams.min_age >= 0 && this.dataparams.max_age) {
                    this.setTimeouts = setTimeout(() => {
                        if (this.dataparams.min_age > this.dataparams.max_age) {
                            this.$Message.error('请输入合理的年龄范围')
                            this.dataparams.max_age = null
                        } else {
                            this.screentask()
                        }
                    }, 1000)
                }
                if (!this.dataparams.min_age && !this.dataparams.max_age) {
                    this.screentask()
                }
            },
            handleAddItem() {
                this.dataparams.push_list.push(
                    {
                        department_id: "",
                        member_ids: [],
                        personList: [],
                    }
                )
            },
            handleRemove(index) {
                this.dataparams.push_list.splice(index, 1)
                this.disabledstatus.splice(index, 1)
            },
            handleCancel() {
                this.$refs.formItem.resetFields()
                this.addView = false;
            },
            handleSubmit() {
                this.$refs.formItem.validate((valid) => {
                    if (valid) {
                        this.isDisable = true
                        setTimeout(() => {
                            this.isDisable = false
                        }, 5000)
                        let list = []
                        for (let item of this.dataparams.push_list) {
                            list.push({ department_id: item.department_id, member_id: item.member_ids })
                        }
                        let params = {
                            id: this.dataparams.id, // 视图ID 新增时不传	是
                            title: this.dataparams.title, // 标题 是	
                            type: 1, // 0：常规视图 1：动态视图
                            push_list: JSON.stringify(list), // 推送到 [json]
                            start_time: this.timers[0] || '',
                            end_time: this.timers[1] || '',
                            patient_diseases_id: this.dataparams.patient_diseases_id.join(','),
                            channel_id: this.dataparams.channel_id.join(','),
                            city_id: this.dataparams.city_id.join(','),
                            min_age: this.dataparams.min_age,
                            max_age: this.dataparams.max_age,
                            patient_status_id: this.dataparams.patient_status_id.join(','),
                            body_parts_id: this.dataparams.body_parts_id.join(','),
                        }
                        settingviewcreateview(params).then((res) => {
                            if (params.id) this.$Message.success('编辑动态成功');
                            else this.$Message.success('新增动态成功');
                            this.loading = false;
                            this.isDisable = false
                            this.addView = false;
                            this.$emit('on-closes');
                        }).catch(() => {
                            this.loading = false;
                            this.isDisable = false
                        })
                    }
                })
            },
        },
    };
</script>
<style scoped>
</style>